package com.buercorp.wangyu.core1.ch7.stackTrace;

import java.util.Scanner;


/**
 * A program that display a trace feature of a recursive method call.
 *
 * @author Cay Horstmann
 */
public class StackTrace { // 堆栈跟踪
    /**
     * COmputes the factorial of a number
     * 阶乘
     *
     * @param n a non-negative integer
     * @return n! = 1 * 2 * 3.....* n
     */
    public static int factorial(int n) {
        System.out.println("factorial(" + n + "):");
        var walker = StackWalker.getInstance();
        walker.forEach(System.out::println);
        int r;
        if (n <= 1) r = 1;
        else r = n * factorial(n - 1);
        System.out.println("return " + r);
        return r;
    }


    public static void main(String[] args) {
        try (var in = new Scanner(System.in)) {
            System.out.print("Enter n: ");
            int n = in.nextInt();
            factorial(n);
        }
    }
}


